package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.INVMLMapper;
import com.example.service.INVMLService;
import com.example.entity.mes.INVML;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Slf4j
public class INVMLServiceImpl extends ServiceImpl<INVMLMapper, INVML> implements INVMLService {

    /**
     * 批量保存或更新数据
     * @param dataList 数据列表
     * @return 是否处理成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateBatchData(List<INVML> dataList) {
        try {
            // 每批次处理的数量
            int batchSize = 500;
            LocalDateTime now = LocalDateTime.now();
            // 格式化日期时间部分
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String dateTimePart = now.format(formatter);
            // 获取毫秒部分
            int milli = now.getNano() / 1000000;
            // 拼接日期时间部分和毫秒部分
            String time = dateTimePart + String.format("%03d", milli);

            // 分批处理
            for (int i = 0; i < dataList.size(); i += batchSize) {
                int endIndex = Math.min(i + batchSize, dataList.size());
                List<INVML> subList = dataList.subList(i, endIndex);

                for (INVML invml : subList) {
                    // 构建查询条件（根据唯一键）
                    LambdaQueryWrapper<INVML> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(INVML::getMl001, invml.getMl001())
                            .eq(INVML::getMl003, invml.getMl003());
                    // 查询是否存在
                    INVML existInvml = this.getOne(queryWrapper);

                    if (existInvml != null) {
                        // 存在则更新
                        invml.setModifier("ERP");
                        invml.setModiDate(time);
                        this.update(invml, queryWrapper);
                    } else {
                        // 不存在则插入
                        invml.setCreator("ERP");
                        invml.setCreateDate(time);
                        invml.setModifier("ERP");
                        invml.setModiDate(time);
                        this.save(invml);
                    }
                }

                log.info("成功处理第{}批数据，本批数量：{}", (i / batchSize + 1), subList.size());
            }
            return true;
        } catch (Exception e) {
            log.error("批量保存或更新数据失败", e);
            throw new RuntimeException("批量保存或更新数据失败：" + e.getMessage());
        }
    }
}
